<?php
// +----------------------------------------------------------------------
// | VueAdmin框架[基于ThinkPHP5开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2018 http://www.vueadmin.org
// +----------------------------------------------------------------------
// | VueAdmin承诺基础框架永久免费开源，您可用于学习和商用，但必须保留软件版权信息。
// +----------------------------------------------------------------------
// | Author: sept <917088650@qq.com>，开发者QQ群：63131383
// +----------------------------------------------------------------------

namespace app\system\model;

use app\lib\Auth\Auth;
use app\lib\exception\ApiException;
use app\lib\exception\ForbiddenException;
use app\lib\exception\MissException;
use app\lib\returnCode\Code;
use app\lib\returnCode\Msg;

class AdminMenu extends Base
{
// 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = false;

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    /**
     * 保存入库
     * @param array $data
     * @author sept <917088650@qq.com>
     * @return bool
     */
    public function storage($data = [], $id = 0)
    {
        // system菜单 只允许超级管理员在开发模式下修改
        if (isset($data['id']) && !empty($data['id'])) {
            if ($data['system'] == 1 && (Auth::id != 1 || config('sys.app_debug') == 0)) {
                //禁止修改系统模块
                throw new ApiException(Code::USER_POWER_ERROR,Msg::USER_POWER_ERROR);
            }
        }

        $data['url'] = trim($data['url'], '/');

        if (isset($id) && !empty($id)) {
            $res = $this->where('id','=',$id)->update($data);
        } else {
            $res = $this->create($data);
        }

        return $res;
    }

    /**
     * 获取指定节点下的所有子节点
     * @param int $pid 父级ID
     * @param int $status
     * @param string $field
     * @author sept <917088650@qq.com>
     * @return array|mixed
     */
    public static function getAllChild($pid = 0, $status = 1, $field = 'id,pid,title,url,sort,status')
    {
        $cache_tag = md5('_admin_child_menu'.$pid.$field.$status);
        $data = [];
        if (config('app_debug') == 0) {
            $data = cache($cache_tag);
        }
        if (empty($data)) {
            $map = [];
            if ($status == 1) {
                $map['status'] = 1;
            }

            $data = self::where($map)->where('pid','=',$pid)->order('sort asc')->column($field);
            $data = array_values($data);
            // 非开发模式，缓存菜单
            if (config('sys.app_debug') == 0) {
                cache($cache_tag, $data);
            }
        }
        return $data;
    }


    /**
     * 获取当前访问节点信息，支持扩展参数筛查
     * @param int $id
     * @author sept <917088650@qq.com>
     * @return array|bool|\PDOStatement|string|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getInfo($id = 0)
    {
        $map = [];
        if (empty($id)) {
            $model      = request()->module();
            $controller = request()->controller();
            $action     = request()->action();
            $map['url'] = $model.'/'.$controller.'/'.$action;
        } else {
            $map['id'] = (int)$id;
        }

        $map['status'] = 1;
        $row = self::where($map)->field('id,title,url')->find();


        if (!$row) {
            //菜单节点不存在或者已禁用
            throw new ApiException(Code::MENT_ERROR_FIND_NULL,Msg::MENT_ERROR_FIND_NULL);
        }

        return $row;
    }

    /**
     * 根据指定节点找出顶级节点的ID
     * @param int $id
     * @author sept <917088650@qq.com>
     * @return int|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getParents($id = 0)
    {
        $map = [];
        if (empty($id)) {
            $model      = request()->module();
            $controller = request()->controller();
            $action     = request()->action();
            $map['url'] = $model.'/'.$controller.'/'.$action;
        } else {
            $map['id'] = (int)$id;
        }
        $res = self::where($map)->find();
        if ($res['pid'] > 0) {
            $id = self::getParents($res['pid']);
        } else {
            $id = $res['id'];
        }
        return $id;
    }

    /**
     * 删除菜单
     * @param string $ids
     * @author sept <917088650@qq.com>
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function del($ids = '') {
        if (!is_array($ids)) {
            $ids = explode(",",$ids);
        }
        if (is_array($ids)) {
            foreach ($ids as $k => $v) {
                $map = [];
                $map['id'] = $v;
                $row = self::where($map)->find();
                if ((Auth::id != 1 && $row['system'] == 1)) {
                    throw new ApiException(Code::SYSTEM_NO_BAN_DATA,printf(Msg::SYSTEM_NO_BAN_DATA,$row['title']));
                }
                if (self::where('pid', $row['id'])->find()) {
                    throw new ApiException(Code::SYSTEM_DELETE_NEXT,printf(Msg::SYSTEM_DELETE_NEXT,$row['title']));
                }

                self::where($map)->delete();
            }
            return true;
        }
        return false;
    }

}